<template>
  <div class="main_box">
    <el-row>
      <el-col :span="12">
        <Crumbs></Crumbs>
      </el-col>
      <el-col :span="12">
        <div class="opration_wrap">
          <el-button
            type="primary"
            icon="fa fa-mail-forward"
            @click="returnList"
          >返回</el-button>
        </div>
      </el-col>
    </el-row>
    <div class="add_wrap">
      <div class="tit">
        <h2>基础信息</h2>
      </div>
      <el-form
        :model="goodsForm"
        ref="goodsForm"
        label-width="200px"
        :rules="roleRules"
      >
        <el-row>
          <el-form-item
            label="项目类型"
            prop="classOneId"
          >
            <el-select
              v-model="goodsForm.classOneId"
              filterable
              clearable
              disabled
              reserve-keyword
              :loading="loadingPro"
              placeholder="请输入项目类型"
              :filter-method="listClassOne"
              @change="handleClassOneChange"
            >
              <el-option
                v-for="item in classOneIdList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <!--<el-cascader
              ref="cascaderProject"
              :props="projectProps"
              :loading="loadingPro"
              disabled
              :options="pickProjectList"
              v-model="selectProjectList"
              @change="handleProjectChange"
            >
            </el-cascader>-->
          </el-form-item>

          <el-form-item
            label="医院名称"
            prop="institutionId"
          >
            <!-- <el-input
              v-model="goodsForm.institutionId"
              placeholder="请输入医院名"
            ></el-input> -->
            <el-select
              v-model="goodsForm.institutionId"
              filterable
              clearable
              disabled
              reserve-keyword
              :loading="loadingIns"
              placeholder="请输入医院名"
              :filter-method="listInstitution"
              @change="handleInstitutionChange"
            >
              <el-option
                v-for="item in pickInstitutionList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="产品名称"
            prop="goodsName"
          >
            <el-input
              v-model="goodsForm.goodsName"
              placeholder="商品前缀+属性+描述"
            >
              <template slot="prepend">{{this.goodsForm.projectName}}</template>
            </el-input>
          </el-form-item>
          <!--<el-form-item
            label="治疗医生"
            prop="doctorIds"
          >
            <el-select
              v-model="goodsForm.doctorIds"
              :disabled="false"
              filterable
              multiple
              clearable
              reserve-keyword
              placeholder="请输入医生姓名"
              @change="handleDoctorChange"
              @focus="listDoctor"
            >
              <el-option
                v-for="item in pickDoctorList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>

          </el-form-item>-->
          <!--<el-col>-->
            <el-form-item
              label="服务承诺"
              prop="servicePromise"
            >
              <!-- <el-radio-group v-model="goodsForm.servicePromise">
                <el-radio :label="1">无隐形消费</el-radio>
                <el-radio :label="2">未使用随时退</el-radio>
                <el-radio :label="3">需提前7天预约</el-radio>
              </el-radio-group> -->
              <el-select
                v-model="goodsForm.servicePromise"
                clearable
                placeholder="请选择服务承诺"
              >
                <el-option
                  v-for="item in servicePromiseOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >

                </el-option>
              </el-select>

            </el-form-item>
          <!--</el-col>-->
        </el-row>
        <div class="tit">
          <h2>上传产品图片</h2>
        </div>
        <el-row :gutter="20">
          <!-- <el-col :span="6">
            <div class="grid-content bg-purple">
               <el-form-item class="img_item" prop="goodsImageOneUrl">
                <div class="img">
                  <img :src="goodsForm.goodsImageOneUrl">
                  <i class="el-icon-plus" v-if="!goodsForm.goodsImageOneUrl"></i>
                </div>
                <div class="txt">
                  <span>商品图片一(封面)</span>
                </div>
                <el-input
                  type="file"
                  @change="handleFile('goodsImageOne','goodsImageOneUrl')"
                  id="goodsImageOne"
                  class="file"
                ></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
               <el-form-item class="img_item" prop="goodsImageTwoUrl">
                <div class="img">
                  <img :src="goodsForm.goodsImageTwoUrl">
                  <i class="el-icon-plus" v-if="!goodsForm.goodsImageTwoUrl"></i>
                </div>
                <div class="txt">
                  <span>商品图片二</span>
                </div>
                <el-input
                  type="file"
                  @change="handleFile('goodsImageTwo','goodsImageTwoUrl')"
                  id="goodsImageTwo"
                  class="file"
                ></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
               <el-form-item class="img_item" prop="goodsImageThreeUrl">
                <div class="img">
                  <img :src="goodsForm.goodsImageThreeUrl">
                  <i class="el-icon-plus" v-if="!goodsForm.goodsImageThreeUrl"></i>
                </div>
                <div class="txt">
                  <span>商品图片三</span>
                </div>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
              <el-form-item label="商品图片四" class="img_item" prop="goodsImageFourUrl">
                <div class="img">
                  <img :src="goodsForm.goodsImageFourUrl">
                  <i class="el-icon-plus" v-if="!goodsForm.goodsImageFourUrl"></i>
                </div>
                <div class="txt">
                  <span>商品图片四</span>
                </div>
              </el-form-item>
            </div>
          </el-col> -->

          <div>

            <el-upload
              :auto-upload="false"
              :action="uploadUrl"
              list-type="picture-card"
              ref="upload"
              drag
              :http-request="fnUploadRequest"
              :before-upload="fnBeforeUpload"
              :on-success="fnUploadSuccess"
              :on-exceed="fnUploadExceed"
              :on-change="fnUploadChange"
              :headers="uploadHeaders"
              :file-list="fileList"
              :limit="files"
              :disabled="disabled"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <i class="el-icon-plus"></i>
              <!-- <i class="el-icon-upload"></i> -->
              <!-- <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div> -->
              <div
                slot="tip"
                class="el-upload-tip"
              >
                <ul style="margin-top: 50px;">
                  <li>1、至少上传一张,最多四张图片，第一张将会设为封面</li>
                  <li>2、图片文件大小不能超过1M</li>
                  <li>3、图片必须为正方形且图片尺寸必须大于或等于400×400（谨慎缩放，不然会导致图片模糊）</li>
                  <li>4、支持JPG,PNG格式</li>
                  <li>5、点击右上角的删除图片，单击换图</li>
                  <li>6、拖拽图片即可以实现图片的更换</li>
                  <li>7、请上传有版权且图像清晰的美女头像、仪器设备或针剂产品图片</li>
                </ul>
              </div>

            </el-upload>
            <el-dialog :visible.sync="dialogVisible" >
              <img
                width="100%"
                :src="dialogImageUrl"
                alt=""
              >
            </el-dialog>
            <el-button
              size="small"
              type="success"
              @click="submitUpload"
            >上传到服务器</el-button>
            <!-- 至少上传一张封面图片 -->
            <el-form-item
              label=""
              prop="goodsImageOneUrl"
            >
              <el-input
                type="hidden"
                v-model="goodsForm.goodsImageOneUrl"
              ></el-input>
            </el-form-item>

          </div>
        </el-row>

        <div class="tit">
          <h2>商品介绍</h2>
        </div>
        <el-row>
          <div style="width:100%;">
            <ul>
              <li>禁止留微信，电话，QQ等联系方式</li>
              <li>产品详情如含有价格应与提报价一致</li>
              <li>假体隆鼻或下巴隆胸等需放假体项目必须写明假体品牌</li>
              <li>手续类项目必须写明提报价有无包含麻醉费用或其他隐性消费</li>
              <li>不能含有"最"字，比如"最好"等字眼</li>
              <li>上传图片尺寸宽度为706px</li>
            </ul>
            <Editor
              class="editor"
              v-model="goodsForm.goodsDetails"
              :setting="editorSetting"
              @show="editors"
              :url="Url"
              :max-size="MaxSize"
              :accept="Accept"
              :with-credentials="withCredentials"
              @on-upload-fail="onEditorReady"
              @on-upload-success="onEditorUploadComplete"
            ></Editor>
          </div>
        </el-row>

        <div class="tit">
          <h2>完善产品价格</h2>
        </div>
        <el-row>
          <el-form-item
            label="商品最低价格"
            prop="retailPrice"
          >
            <el-input v-model="goodsForm.retailPrice"></el-input>
          </el-form-item>
          <el-form-item
            label="商品最高价格"
            prop="platformPrice"
          >
            <el-input v-model="goodsForm.platformPrice"></el-input>
          </el-form-item>
          <el-form-item
            label="商品数量"
            prop="surplusNum"
          >
            <el-input v-model="goodsForm.surplusNum"></el-input>
          </el-form-item>
          <el-form-item
            label="限购数量"
            prop="mostNum"
          >
            <el-input v-model="goodsForm.mostNum"></el-input>
          </el-form-item>

          <!--<el-form-item
            label="是否支持花花卡"
            prop="isFlower"
          >
            <el-radio-group v-model="goodsForm.isFlower">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="是否套餐商品"
            prop="isMeal"
          >
            <el-radio-group v-model="goodsForm.isMeal">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>-->
        </el-row>

        <!--<div class="tit">
          <h2>商品其他信息</h2>
        </div>
        <div style="margin-top:15px">
          &lt;!&ndash; <fieldset>
          <legend style="font-size:16px">商品其他信息</legend> &ndash;&gt;
          <el-form-item
            label="服务承诺时间"
            prop="serviceTimeType"
          >
            <el-col :span="11">
              &lt;!&ndash; <el-radio-group v-model="goodsForm.serviceTimeType">
              <el-radio :label="1">一个月</el-radio>
              <el-radio :label="2">两个月</el-radio>
              <el-radio :label="3">三个月</el-radio>
              <el-radio :label="4">自定义</el-radio>
            </el-radio-group> &ndash;&gt;
              <el-select
                v-model="goodsForm.serviceTimeType"
                placeholder="请选择"
                @change="$set(goodsForm, goodsForm.serviceTimeType, $event)"
              >
                <el-option
                  v-for="item in serviceTimeTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="11">

              &lt;!&ndash; <el-input-number :min="4"
              v-model="goodsForm.serviceTimeRemark"
             ></el-input-number> &ndash;&gt;

              &lt;!&ndash; v-show="goodsForm.serviceTimeType == 4"              &ndash;&gt;
              <el-input-number
                v-show="goodsForm.serviceTimeType == 4"
                v-model="goodsForm.serviceTimeRemark"
                controls-position="right"
                :min="1"
                :max="999"
                :controls='false'
                placeholder="自定义"
              ></el-input-number>
            </el-col>
          </el-form-item>

          <el-form-item
            label="商品使用时间"
            prop="useTimeType"
          >
            <el-col :span="11">
              <el-radio-group v-model="goodsForm.useTimeType">
                <el-radio :label="1">医院正常营业时间均可</el-radio>
                <el-radio :label="2">自定义</el-radio>
              </el-radio-group>
            </el-col>
            <el-col :span="11">
              &lt;!&ndash; <p>组件值：{{ goodsForm.useTimeStEnd }}</p>
                form提交时赋值
                <p>组件值useTimeBegin：{{ goodsForm.useTimeBegin= goodsForm.useTimeStEnd[0] }}</p>
                <p>组件值useTimeEnd：{{ goodsForm.userTimeEnd = goodsForm.useTimeStEnd[1]}}</p> &ndash;&gt;

              &lt;!&ndash; v-show="goodsForm.useTimeType ==2" &ndash;&gt;
              <el-date-picker
                v-show="goodsForm.useTimeType ==2"
                v-model="goodsForm.useTimeStEnd"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-col>
          </el-form-item>
        </div>-->
        <!-- </fieldset> -->

        <div class="tit">
          <h2>添加商品规格</h2>
        </div>

        <el-row>



          <el-form :rules="model.rules" :model="model"  ref="form">

            <el-form-item
              label="选择规格（可多选）"
              prop="selectedSpecList"
              style="margin-bottom: 20px"
            >
              <el-select
                v-model="model.selectedSpecList"
                placeholder="选择规格"
                multiple
                @visible-change="getSpecList"
                @change="onSpecListChanged"
              >
                <el-option
                  v-for="item in model.specList"
                  :key="item.specId"
                  :label="item.specName"
                  :value="item.specId"
                >
                </el-option>
              </el-select>
              <p style="color: #ff0000;">*变动规格会导致数据清空，请先选好规格再填写</p>
              <p style="color: #ff0000;">*库存为必填数据，不填写将导致数据无法提交</p>
            </el-form-item>

            <!-- 表布局 -->


            <el-table
              border
              :data="model.tableData"
              style="width: 100%;"
              v-if="model.selectedSpecList.length > 0"
              max-height="320"
            >

              <el-table-column
                width="320px"
                v-for="(itemRow,index) in specs"
                :label="itemRow.rowName">
                <template slot-scope="scope">
                  <el-form-item :prop="'itemRow.rowValue'" style="margin-bottom: 20px;margin-top: 20px">

                    <!--<el-input style="width:80px"  v-model="" ></el-input>-->

                    <el-select
                      v-model="scope.row.specsValue[index]"
                      filterable
                      allow-create
                      default-first-option
                      placeholder="选择或输入具体规格">
                      <el-option
                        v-for="item in itemRow.specValueList"
                        :key="item.sid"
                        :label="item.sval"
                        :value="item.sval">
                      </el-option>
                    </el-select>

                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                width="140px"
                label="库存">
                <template slot-scope="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.stock'" style="margin-bottom: 28px;margin-top: 28px">
                    <el-input style="width:80px"  v-model="scope.row.stock" ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                width="140px"
                label="最低价格">
                <template slot-scope="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.minPrice'" style="margin-bottom: 28px;margin-top: 28px" >
                    <div style="height: 100%;display: flex; align-items: center; justify-content: center" >
                      <el-input style="width:80px"  v-model="scope.row.minPrice" ></el-input>
                    </div>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                width="140px"
                label="最高价格">
                <template slot-scope="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.maxPrice'" style="margin-bottom: 28px;margin-top: 28px" >
                    <div style="height: 100%;display: flex; align-items: center; justify-content: center" >
                      <el-input style="width:80px"  v-model="scope.row.maxPrice" ></el-input>
                    </div>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                label="操作"
                fixed="right"
                min-width="200"
              >
                <template slot-scope="scope">
                  <el-button size="small" @click="deleteSpecs(scope.row)" >删除</el-button>
                  <el-button size="small" v-if="scope.$index == model.tableData.length-1" @click="addSpecs(scope.row)" >添加</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-row>

        <el-row>
          <el-form-item style="float:right">
            <el-button @click="returnList">关 闭</el-button>
            <el-button
              type="primary"
              @click="sureGoodsClick(1)"
            >保 存</el-button>
            <el-button
              type="primary"
              @click="sureGoodsClick(2)"
            >保存并送审</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
  import * as validators from '@/utils/validators'
  import * as message from '@/constants/message'
  import Crumbs from '@/components/Crumbs'
  import Map from '@/components/MapComponent'
  import Editor from '@/components/Editor' // 根据editor.vue组件位置引入
  import { mapGetters, mapActions } from 'vuex'
  export default {
    props: {},
    data () {
      return {
        servicePromiseOptions: [
          {
            value: '1',
            label: '无隐形消费'
          },
          {
            value: '2',
            label: '未使用随时退'
          },
          {
            value: '3',
            label: '需提前7天预约'
          }
        ],
        /*pickProjectList: [],
        selectProjectList: [],
        projectProps: {
          label: 'className',
          value: 'classId'
        },
        pickDoctorList: [],*/
        classOneIdList: [],
        pickInstitutionList: [],
        loadingIns: false,
        //loadingDoc: false,
        loadingPro: false,
        serviceTimeTypeOptions: [
          {
            value: 30,
            label: '30天'
          },
          {
            value: 60,
            label: '60天'
          },
          {
            value: 90,
            label: '90天'
          },
          {
            value: 4,
            label: '自定义'
          }
        ],
        uploadUrl: '',
        uploadFileLength: 0,
        uploadFileSuccess: 0,
        uploadFileNames: [],
        uploadFileName: [],
        goodsData: "",
        fileList: [],
        files: 4,
        disabled: false,
        uploadHeaders: {
          authorization: ''
        },
        dialogImageUrl: '',
        dialogVisible: false,
        goodsForm: {
          goodsId: '',
          classOneId: '',
          classOneName: '',
          /*classTwoId: '',
          classTwoName: '',
          projectId: '',
          projectName: '',*/
          goodsName: '',
          institutionId: '',
          //doctorIds: [],
          servicePromise: '',
          goodsImageOneUrl: '',
          goodsImageTwoUrl: '',
          goodsImageThreeUrl: '',
          goodsImageFourUrl: '',
          //goodsType: '',
          retailPrice: '',
          platformPrice: '',
          //isFlower: '',
          //isMeal: '',
          surplusNum: '',
          mostNum: '',
          /*serviceTimeType: '',
          serviceTimeRemark: '',
          useTimeType: '',
          useTimeBegin: '',
          useTimeEnd: '',
          useTimeStEnd: '',*/
          goodsDetails: ''
        },
        editorSetting: {
          // 配置富文本编辑器高
          height: 200
        },
        Url: this.$Config.api.uploadOssApi, // 图片对应的上传地址
        MaxSize: 1048576, // 文件大小 1M
        Accept: 'image/jpeg, image/png', // 文件格式
        withCredentials: true,
        content: '', // 富文本编辑器双向绑定的内容
        roleRules: {
          classOneId: [
            {
              required: true,
              message: '请输入项目',
              trigger: 'blur'
            }
          ],
          goodsName: [
            {
              required: true,
              message: '请输入商品名称',
              trigger: 'blur'
            }
          ],
          institutionId: [
            {
              required: true,
              message: '请输入医院',
              trigger: 'blur'
            }
          ],
          /*doctorIds: [
            {
              required: true,
              message: '请输入医生',
              trigger: 'blur'
            }
          ],*/
          servicePromise: [
            {
              required: true,
              message: '请输入服务承诺',
              trigger: 'blur'
            }
          ],
          goodsImageOneUrl: [
            {
              required: true,
              message: '请输入商品（封面）',
              trigger: 'blur'
            }
          ],
          surplusNum: [
            {
              required: true,
              message: '商品数量',
              trigger: 'blur'
            }
          ],
          /*mostNum: [
            {
              required: true,
              message: '限购数量',
              trigger: 'blur'
            }
          ],*/
          retailPrice: [
            {
              required: true,
              message: '请输入最低价格',
              trigger: 'blur'
            }
          ],
          platformPrice: [
            {
              required: true,
              message: '请输入最高价格',
              trigger: 'blur'
            }
          ],
          /*serviceTimeType: [
            {
              required: true,
              message: '服务承诺时间',
              trigger: 'blur'
            }
          ],
          useTimeType: [
            {
              required: true,
              message: '商品使用时间',
              trigger: 'blur'
            }
          ],*/
          mostNum: [
            {
              required: true,
              message: '商品限购数量',
              trigger: 'blur'
            }
          ],
          goodsDetails: [
            {
              required: true,
              message: '商品详情',
              trigger: 'blur'
            }
          ]
        },
        model:{
          specList:[],
          selectedSpecList:[],
          rules: {
            stock:{ type:"string",required:true,message:"必须填写库存",trigger:"blur"}
          },
          tableData:[{
            stock:"",
            maxPrice:"",
            minPrice:"",
            specsValue:[],
          }]
        },
        specs:[
        ],
      }
    },
    components: {
      Crumbs,
      Editor,
      Map
    },
    methods: {
      ...mapGetters({
        openTabs: 'getOpenTabs'
      }),
      ...mapActions({
        setOpenTabs: 'setOpenTabs',
        setActiveIndexPath: 'setActiveIndexPath',
        setDeleteTabs: 'setDeleteTabs',
        replaceOpenTab: 'replaceOpenTab'
      }),

      getDetail () {
        let _this = this;
        this.$Get(this.$Config.api.goodsDetail, {
          goodsId: this.$route.query.id
        }).then(res => {
          _this.goodsForm.goodsDetails = res.data.goodsDetails
        })
      },
      getData() {
        let _this = this;
        this.$Get(this.$Config.api.goods, {
          goodsId: this.$route.query.id
        }).then(res => {
          _this.goodsData = res.data;
          _this.goodsForm =  _this.goodsData;
          _this.getSpecList()
          if (_this.goodsData.goodsImageOneUrl) {
            _this.fileList.push({name:'one', url: _this.goodsData.goodsImageOneUrl})
          }
          if (_this.goodsData.goodsImageTwoUrl) {
            _this.fileList.push({name:'two', url: _this.goodsData.goodsImageTwoUrl})
          }
          if (_this.goodsData.goodsImageThreeUrl) {
            _this.fileList.push({name:'three', url: _this.goodsData.goodsImageThreeUrl})
          }
          if (_this.goodsData.goodsImageFourUrl) {
            _this.fileList.push({name:'four', url: _this.goodsData.goodsImageFourUrl})
          }

          _this.goodsForm.serviceTimeType =  _this.goodsData.serviceDays;

          _this.model.selectedSpecList = [];
          _this.model.specList = _this.goodsData.goodsSpecList;
          for (let i = 0; i < _this.goodsData.goodsSpecList.length; i++) {
            _this.model.selectedSpecList.push(_this.goodsData.goodsSpecList[i].specId);
            _this.specs.push({
              rowName: _this.goodsData.goodsSpecList[i].specName,
              rowKey: _this.goodsData.goodsSpecList[i].specId,
              rowValue: _this.goodsData.goodsSpecList[i].specId,
              specValueList: _this.goodsData.goodsSpecList[i].specValueList
            })
          }
          _this.model.tableData = [];
          for (let i = 0; i < _this.goodsData.goodsProductList.length; i++) {
            let itemData = _this.goodsData.goodsProductList[i];
            let specsValueTemp = itemData.specNames.split(",")
            _this.model.tableData.push({
              stock: itemData.surplusNum,
              maxPrice: itemData.platformPrice,
              minPrice: itemData.retailPrice,
              specsValue: specsValueTemp
            })
          }

          console.log("selectedSpecList --->  " + JSON.stringify(_this.model.selectedSpecList))
          console.log("specList --->  " + JSON.stringify(_this.model.specList))
          console.log("tableData --->  " + JSON.stringify(_this.model.tableData))

          // _this.model
          /*if (_this.goodsData.doctorIds.indexOf(",") != -1) {
            let doctorIds = _this.goodsData.doctorIds.split(",");
            if (doctorIds.length > 0) {
              let tempArray = [];
              for (let i = 0; i < doctorIds.length; i++) {
                tempArray[i] = parseInt(doctorIds[i]);
              }
              _this.goodsForm.doctorIds = tempArray;
            }
          }else if (_this.goodsData.doctorIds) {
            let doctor = parseInt(_this.goodsData.doctorIds);
            _this.goodsForm.doctorIds = [];
            _this.goodsForm.doctorIds[0] = doctor;
          }*/
          /*console.log("12--->" + JSON.stringify(_this.goodsForm.doctorIds));


          let ids =  _this.goodsData.goodsProjectIds.split(",");
          ids.forEach((item,index)=>{
            _this.selectProjectList[index] = parseInt(item);
          });
          console.log("--->" + JSON.stringify(_this.selectProjectList))
          _this.listDoctor("")*/
          // this.goodsForm.classOneId =  this.goodsData.classOneId;
          // this.goodsForm.classOneName =  this.goodsData.classOneName;
          // this.goodsForm.classTwoId =  this.goodsData.classTwoId;
          // this.goodsForm.classTwoName =  this.goodsData.classTwoName;
          // this.goodsForm.projectId =  this.goodsData.projectId;
          // this.goodsForm.projectName =  this.goodsData.projectName;
          // this.goodsForm.goodsName =  this.goodsData.goodsName;
          // this.goodsForm.institutionId =  this.goodsData.institutionId;
          // this.goodsForm.doctorIds =  this.goodsData.doctorIds;
          // this.goodsForm.servicePromise =  this.goodsData.servicePromise;
          // this.goodsForm.goodsImageOneUrl =  this.goodsData.goodsImageOneUrl;
          // this.goodsForm.goodsImageTwoUrl =  this.goodsData.goodsImageTwoUrl;
          // this.goodsForm.goodsImageThreeUrl =  this.goodsData.goodsImageThreeUrl;
          // this.goodsForm.goodsImageFourUrl =  this.goodsData.goodsImageFourUrl;
          // this.goodsForm.goodsType =  this.goodsData.goodsType;


        });
      },
      init () {
        let _this = this
        _this.getData();
        _this.getDetail();
        _this.listInstitution()
        _this.listClassOne()
      },
      // Editors
      editors (content) {
        // editor组件传过来的值赋给content
        console.log('editors>>>' + content)
        this.goodsForm.goodsDetails = content
      },
      onEditorReady (ins, ina) {
        // 上传失败的函数
        console.log('ins')
        console.log(ins)
        console.log(ina)
      },
      onEditorUploadComplete (json) {
        // 处理上传图片后返回数据，添加img标签到编辑框内
        console.log('json')
        console.log(json)
        console.log(json[0].location)
        this.content =
          this.content +
          '<img src=http://localhost:8008/' +
          json[0].location +
          '>'
      },
      sureGoodsClick (val) {
        let _this = this
        let msg = ''
        if (val === 1) {
          msg = message.MSG_CONFIRM_SAVE_ALTER
        } else if (val === 2) {
          msg = message.MSG_CONFIRM_SAVE_COMMIT_ALTER
        } else {
          return '操作类型有误！'
        }
        this.$refs.goodsForm.validate(valid => {
          if (valid) {
            _this.$confirm(msg, message.TITLE_PROMPT, {}).then(() => {
              _this.updateGoods(val)
            })
          }
        })
      },

      getSpecList () {
        let _this = this;
        if (_this.goodsForm.institutionId){
          _this
            .$Get(_this.$Config.api.listByParam,{institutionId:_this.goodsForm.institutionId})
            .then(res => {
              _this.model.specList = res.data;
            })
            .catch(error => {
              _this.model.specList = []
              console.error(error)
            })
        }else{
          _this.$message.error('请先选择医院');
        }
      },
      onSpecListChanged(){
        this.model.tableData = [{
          stock:"",
          maxPrice:"",
          minPrice:"",
          specsValue:[]
        }]
        this.specs = [];
        for(let i = 0; i < this.model.specList.length; i++){
          for(let j = 0; j < this.model.selectedSpecList.length; j++){
            console.log("ttt->" +JSON.stringify(this.model.specList[i]));
            if (this.model.selectedSpecList[j] == this.model.specList[i].specId) {
              this.specs.push({
                rowName: this.model.specList[i].specName,
                rowKey: this.model.specList[i].specId,
                rowValue: this.model.specList[i].specId,
                specValueList: this.model.specList[i].specValueList
              })
            }
          }
        }
        console.log("aaa---->  " + JSON.stringify(this.specs))
      },

      addSpecs(row){
        this.model.tableData.push({
          stock:"",
          maxPrice:"",
          minPrice:"",
          specsValue:[]
        })
      },
      deleteSpecs(row){
        this.model.tableData.splice(row.$index,1)
      },
      updateGoods (val) {
        let _this = this
        let productParam = [];
        for(let i = 0; i < this.model.tableData.length; i++){
          let specStr = this.model.tableData[i].specsValue.join(",");
          let specJsonStr = [];
          for (let j = 0; j < this.model.tableData[i].specsValue.length; j++) {
            specJsonStr.push({
              specType : 1,
              specName : this.specs[j].rowName,
              specId : this.specs[j].rowKey,
              specValue : this.model.tableData[i].specsValue[j]
            })
          }
          productParam.push(
            {
              platformPrice: this.model.tableData[i].maxPrice,
              retailPrice: this.model.tableData[i].minPrice,
              surplusNum: this.model.tableData[i].stock,
              specNames: specStr,
              specArray: JSON.stringify(specJsonStr)
            }
          )
        }
        let goodsFormData = {
          goodsId: _this.goodsForm.goodsId,
          classOneId: _this.goodsForm.classOneId,
          classOneName: _this.goodsForm.classOneName,
          /*classTwoId: _this.goodsForm.classTwoId,
          classTwoName: _this.goodsForm.classTwoName,
          projectId: _this.goodsForm.projectId,
          projectName: _this.goodsForm.projectName,*/
          goodsName: _this.goodsForm.goodsName,
          institutionId: _this.goodsForm.institutionId,
          /*doctorIds:
            _this.goodsForm.doctorIds == null
              ? ''
              : _this.goodsForm.doctorIds.join(','),*/
          servicePromise: _this.goodsForm.servicePromise,
          goodsImageOneUrl: _this.goodsForm.goodsImageOneUrl.replace("blob:",""),
          goodsImageTwoUrl: _this.goodsForm.goodsImageTwoUrl,
          goodsImageThreeUrl: _this.goodsForm.goodsImageThreeUrl,
          goodsImageFourUrl: _this.goodsForm.goodsImageFourUrl,
          // goodsType: _this.goodsForm.goodsType,
          retailPrice: _this.goodsForm.retailPrice,
          platformPrice: _this.goodsForm.platformPrice,
          /*isFlower: _this.goodsForm.isFlower,
          isMeal: _this.goodsForm.isMeal,*/
          surplusNum: _this.goodsForm.surplusNum,
          mostNum: _this.goodsForm.mostNum < 1 ? 1 : _this.goodsForm.mostNum,
          /*serviceDays:
            _this.goodsForm.serviceTimeType === 4
              ? _this.goodsForm.serviceTimeRemark
              : _this.goodsForm.serviceTimeType,
          useTimeType: _this.goodsForm.useTimeType,
          useTimeBegin:
            _this.goodsForm.useTimeTyp === 3 ? _this.goodsForm.useTimeBegin : '',
          useTimeEnd:
            _this.goodsForm.useTimeTyp === 3 ? _this.goodsForm.useTimeEnd : '',*/
          goodsDetails: _this.goodsForm.goodsDetails,
          productAddParam : productParam
        }

        if (val === 1) {
          console.log('====保存===')
          goodsFormData.approveState = 2
        } else if (val === 2) {
          console.log('====保存并提交审核===')
          goodsFormData.approveState = 0
        }

        console.log('add>>>>' + goodsFormData)
        // TODO
        _this
          .$Put(_this.$Config.api.goods, goodsFormData)
          .then(data => {
            _this.$notify.success({
              title: message.TITLE_SUCCESS,
              message: message.MSG_ACTION_SUCCESS
            })
            _this.$router.push({ name: '商品列表' })
          })
          .catch(error => {
            if (error.msg) {
              _this.$notify.error({
                title: message.TITLE_ERROR,
                message: error.msg
              })
            }
          })
      },
      handleClassOneChange(val) {
        let obj = {};
        obj = this.classOneIdList.find((item)=>{
          return item.value === val;
        });
        this.goodsForm.classOneName = obj.label;
      },
      /*handleProjectChange (value) {
        console.log('handleProjectChange>>>>' + value)
        let _this = this
        let cascaderProject = _this.$refs['cascaderProject']
        let projectValue = cascaderProject.currentValue
        let projectLables = _this.$refs['cascaderProject'].currentLabels
        console.log('handleProjectChange>>>>' + projectValue[0])
        console.log('handleProjectChange>>>>' + projectLables[0])
        _this.goodsForm.classOneId = projectValue[0]
        _this.goodsForm.classOneName = projectLables[0]

        _this.goodsForm.classTwoId = projectValue[1]
        _this.goodsForm.classTwoName = projectLables[1]

        _this.goodsForm.projectId = projectValue[2]
        _this.goodsForm.projectName = projectLables[2]
        console.log(
          'handleProjectChange>>>>' +
          _this.goodsForm.projectName +
          _this.goodsForm.projectId
        )
        console.log('projectId>>>>' + _this.goodsForm.classOneId)
        // _this.listDoctor()
      },
      listProject (query) {
        let _this = this
        _this.loadingPro = true
        // // page + condition
        // let cond = {
        //   pageNo: 1,
        //   pageSize: 20,
        //   projectName: !query ? '' : query,
        //   approveState: 1,
        //   state: 1
        // }
        // console.log(cond)
        console.log(_this.$Config.api.projectTree)
        _this
          .$Get(_this.$Config.api.projectTree)
          .then(res => {
            setTimeout(() => {
              _this.loadingPro = false
              // _this.pickProjectList = res.data
              _this.pickProjectList = res.data.map(item => {
                return {
                  classId: item.classId,
                  className: item.className,
                  children: item.children
                }
              })
              // 处理子节点为空的情况 TODO:待优化
              _this.removeChildren(_this.pickProjectList)
              console.log('_this.pickProjectList>>>>>' + JSON.stringify(_this.pickProjectList))
            }, 200)
          })
          .catch(error => {
            _this.pickProjectList = []
            console.error(error)
          })
      },
      removeChildren (regions) {
        for (let i = 0, len = regions.length; i < len; i++) {
          if (regions[i].children.length === 0) {
            delete regions[i].children
          } else {
            this.removeChildren(regions[i].children)
          }
        }
      },*/
      handleInstitutionChange (value) {
        let _this = this
        console.log('institutionId>>>>' + value)
        // _this.listDoctor()
        this.goodsForm.doctorIds = [];
      },
     /* handleDoctorChange (value) {
        // let _this = this
        // console.log(
        //   value.join(','),
        //   '_this.goodsForm.doctorIds>>>' + _this.goodsForm.doctorIds
        // )
      },
      listDoctor (query) {
        let _this = this
        _this.loadingDoc = true

        // page + condition
        let cond = {
          pageNo: 1,
          pageSize: 20,
          doctorName: !query || typeof query !== 'string' ? '' : query,
          institutionId: _this.goodsForm.institutionId,
          projectId: _this.goodsForm.classOneId
        }
        if (!cond.institutionId || !cond.projectId) {
          _this.loadingDoc = false
          this.$message({
            message: '操作有误,请先选择项目和医院！',
            type: 'warning'
          })
        }
        console.log('cond.institutionId>>' + cond.institutionId)
        console.log('cond.projectId>>' + cond.projectId)
        console.log('url>>' + _this.$Config.api.getDoctorsByInsPro)

        _this
          .$Get(_this.$Config.api.getDoctorsByInsPro, cond)
          .then(res => {
            setTimeout(() => {
              _this.loadingDoc = false
              _this.pickDoctorList = res.data.map(item => {
                return {
                  value: item.doctorId,
                  label: item.doctorName
                }
              })
              console.log('_this.pickDoctorList>>>>>' + JSON.stringify(_this.pickDoctorList))
            }, 200)
          })
          .catch(error => {
            _this.pickDoctorList = []
            console.error(error)
          })
      },*/
      listInstitution (query) {
        let _this = this
        _this.loadingIns = true
        let cond = {
          pageNo: 1,
          pageSize: 500,
          institutionName: !query || typeof query !== 'string' ? '' : query,
          approveState: 1,
          state: 1
        }
        console.log(cond)
        _this
          .$Get(_this.$Config.api.institus, cond)
          .then(res => {
            setTimeout(() => {
              _this.loadingIns = false
              _this.pickInstitutionList = res.data.list.map(item => {
                return {
                  value: item.institutionId,
                  label: item.institutionName
                }
              })
              console.log(
                '_this.pickInstitutionList>>>>>' + _this.pickInstitutionList
              )
            }, 200)
          })
          .catch(error => {
            _this.pickInstitutionList = []
            console.error(error)
          })
      },
      listClassOne (query) {
        let _this = this
        _this.loadingPro = true
        /*let cond = {
          pageNo: 1,
          pageSize: 200,
          classOneName: !query || typeof query !== 'string' ? '' : query,
          approveState: 1,
          state: 1
        }*/
        _this
          .$Get(_this.$Config.api.projectIds)
          .then(res => {
            setTimeout(() => {
              _this.loadingPro = false
              _this.classOneIdList = res.data.map(item => {
                return {
                  value: item.classId,
                  label: item.className
                }
              })
              console.log(
                '_this.classOneIdList>>>>>' + _this.classOneIdList
              )
            }, 200)
          })
          .catch(error => {
            _this.classOneIdList = []
            console.error(error)
          })
      },
      handleRemove (file, fileList) {
        console.log(file, fileList)
      },

      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      handleFile (id, data) {
        const $target = document.getElementById(id)
        const _this = this
        _this.disabled = true
        this.$Get(_this.$Config.api.uploadOssApi).then(res => {
          let OSS = require('ali-oss')
          let client = new OSS({
            region: _this.$Config.oss.region,
            accessKeyId: res.data.accessKeyId,
            accessKeySecret: res.data.accessKeySecret,
            stsToken: res.data.securityToken,
            bucket: _this.$Config.oss.bucket
          })
          const file = $target.files[0]
          const fileName = file.name
          const fileType = fileName.split("\.")[1];
          let fileTempName = new Date().getTime() + fileName.split("\.")[0];
          if (fileTempName.length > 5){
            fileTempName = fileTempName.substring(0,12);
          }
          const newName = fileTempName +"."+ fileType;
          const storeAs = 'web_images/Goods/' + newName
          const resultUpload = ''
          client
            .put(storeAs, file, {})
            .then(function (r1) {
              let realUrl = r1.url.replace(_this.$Config.oss.ossUrl,_this.$Config.oss.realUrl);
              _this.goodsForm[data] = realUrl
            })
            .catch(function (err) {
              console.error(err)
            })
        })
      },
      async submitUpload (option) {
        // this.disabled = true
        this.$refs.upload.submit()
      },
      async fnUploadRequest (option) {
        console.log(option)
        try {
          let vm = this
          // vm.disabled = true
          // 获取OSS配置信息
          // TODO:OSS+el-upload

          // let ComponentApi = new ComponentApi()

          // let ret = await ComponentApi.fileOssParams()
          const _this = this
          // 已经上传过的不处理：情景先上传成功3个，后补充1个，之前3个会循环调用。
          if (option && option.response && option.response.url) {
            return
          }
          _this.$Get(_this.$Config.api.uploadOssApi).then(res => {
            let OSS = require('ali-oss')
            let client = new OSS({
              region: _this.$Config.oss.region,
              accessKeyId: res.data.accessKeyId,
              accessKeySecret: res.data.accessKeySecret,
              stsToken: res.data.securityToken,
              bucket: _this.$Config.oss.bucket
            })
            // const file = $target.files[0]
            let file = option.file
            if (!this.fnBeforeUpload(file)){
              return
            }
            // const file = this.$refs.upload.uploadFiles[0].raw
            const fileName = file.name;
            const fileType = fileName.split("\.")[1];
            let fileTempName = new Date().getTime() + fileName.split("\.")[0];
            if (fileTempName.length > 5){
              fileTempName = fileTempName.substring(0,12);
            }
            const newName = fileTempName +"."+ fileType;
            const storeAs = 'web_images/' + newName;
            const resultUpload = ''
            console.log('fnUploadRequest>>>>>' + fileName)
            // TODO 测试 注释上传动作
            client
              .put(storeAs, file, {})
              .then(
                // response => {
                //   //debugger
                //   this.fnUploadSuccess(response, file, this.fileList)
                //   console.log('r1.url>>>>>>>>>' + response)
                //   //debugger
                // }

                function (ret) {
                  if (ret.res.statusCode === 200) {
                    option.onSuccess(ret)
                    // 值回传
                    // //debugger
                    option.response = ret
                    let realUrl = r1.url.replace(_this.$Config.oss.ossUrl,_this.$Config.oss.realUrl);
                    ret.url = realUrl;
                    console.log('r1.url>>>>>>>>>' + ret.url)
                    return ret
                  } else {
                    option.onError('上传失败')
                  }
                  // _this.goodsForm[data] = r1.url

                  // 赋值
                  // TODO:
                  // file.url = r1.url
                  // console.log('file.url>>>>>>>>>' + file.url)
                }
              )
              .catch(function (err) {
                console.error(err)
              })
          })

          // let ossData = JSON.parse(ret.data.data)
          // let relativePath = ossData.relativePath
          // let client = new OSS.Wrapper({
          //   policy: ossData.policy,
          //   accessKeyId: ossData.accessid,
          //   accessKeySecret: ossData.accesssecret,
          //   bucket: ossData.bucket,
          //   signature: ossData.signature
          // })
          // let file = option.file
          // const point = file.name.lastIndexOf('.')
          // let suffix = file.name.substr(point)
          // let fileName = file.name.substr(0, point)
          // let date = vm.$moment().format('YYYYMMDDHHmm')
          // let fileNames = `${fileName}_${date}${suffix}`
          // // 分片上传文件
          // // ret = await client.multipartUpload(relativePath + fileNames, file, {
          // //   progress: async function (p) {
          // //     let e = {}
          // //     e.percent = p * 100
          // //     option.onProgress(e)
          // //   }
          // // })
          // console.log(fileNames)

          // ret.res.statusCode = 200

          // if (ret.res.statusCode === 200) {
          //   option.onSuccess(ret)
          //   return ret
          // } else {
          //   vm.disabled = false
          //   option.onError('上传失败')
          // }
        } catch (error) {
          console.error(error)
          this.disabled = false
          option.onError('上传失败')
          this.$error(error.message)
        }
      },
      async fnUploadSuccess (response, file, fileLists) {
        console.log('file,>>>>' + JSON.stringify(file));
        // console.log('response,>>>>' + JSON.stringify(response));
        // console.log('fileList,>>>>' + JSON.stringify(fileList));
        // console.log('fileList>>>>' + fileList)
        // console.log('this fileList url>>>>' + fileList[0].name + fileList[0].url)
        // console.log('this fileList url>>>>' + fileList[1].name + fileList[1].url)
        // console.log('this fileList url>>>>' + fileList[2].name + fileList[2].url)
        // //debugger
        // this.$refs.upload.fileList;
        let _this = this
        fileLists.forEach((item, index) => {
          //     _this.goodsForm.goodsImageOneUrl = item.
          if (item.response != undefined && item.response) {
            console.log(index + 'this fileList info:item name>>>>' + item.name + ' local url>>>>' + item.url + ' remote url>>' + item.response.url)
            if (index === 0) {
              _this.goodsForm.goodsImageOneUrl = item.response.url
            } else if (index === 1) {
              _this.goodsForm.goodsImageTwoUrl = item.response.url
            } else if (index === 2) {
              _this.goodsForm.goodsImageThreeUrl = item.response.url
            } else if (index === 3) {
              _this.goodsForm.goodsImageFourUrl = item.response.url
            }
            console.log('_this.goodsForm>>>>>>' + _this.goodsForm.goodsImageOneUrl)
            console.log('_this.goodsForm>>>>>>' + _this.goodsForm.goodsImageFourUrl)
          }
        })
      },
      fnUploadChange () {},
      /**
       * el-upload
       * on-exceed	文件超出个数限制时的钩子
       *  */
      fnUploadExceed (files, fileList) {
        let _this = this
        // _this.$message.warning(`当前限制选择 ${_this.files} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
        _this.$message.warning(`当前限制最多 ${_this.files} 个文件!`)
      },
      fnBeforeUpload (file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isBMP = file.type === 'image/bmp';
        const isLt2M = file.size / 1024 / 1024 < 5;

        if (!isJPG && !isPNG && !isBMP) {
          this.$message.error('上传图片只能是 JPG , PNG , BMP 格式!');
        }

        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 5MB!');
        }
        return (isJPG || isPNG || isBMP) && isLt2M ;
      },
      returnList () {
        this.$router.push({path: '/good/goodManagement'});
      }
    },
    mounted () {
      this.init()
    }
  }
</script>
<style lang="scss" src="@/assets/css/views/add.scss" scope>
  el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 25px;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
  .el-upload-dragger {
    width: 150px;
    height: 150px;
  }
</style>
